//
//  QRCodeViewContoller.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 16/6/22.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewContoller: UIViewController, UITabBarDelegate{
    // 底部视图
    
    // 波图
    @IBOutlet weak var scanImageView: UIImageView!
    // 容器高
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
    // 波上边距
    @IBOutlet weak var scanLineCons: NSLayoutConstraint!
    // 下方bar
    @IBOutlet weak var customTabBar: UITabBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        customTabBar.selectedItem = customTabBar.items![0]
        customTabBar.delegate = self
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 1.动画
        self.startAnimation()
        
        // 2.开始扫描
        startScan()
        
    }
    //MARK: - UITabBarDelegate
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        self.startAnimation()
        if item.tag == 1 {
            print("二维码")
            self.scanLineCons.constant = 300
        } else {
            print("条形码")
            self.scanLineCons.constant = 150
        }
        self.scanImageView.layer.removeAllAnimations()
        self.startAnimation()

    }
    
    private func startAnimation() {
        self.scanLineCons.constant = -self.containerHeightCons.constant
        
        self.scanImageView.layoutIfNeeded()
        // 执行冲击波动画
        UIView.animateWithDuration(2.0, animations: {
            // 1.修改约束
            self.scanLineCons.constant = self.containerHeightCons.constant
            UIView.setAnimationRepeatCount(MAXFLOAT)
            // 2.强制更新约束
            self.scanImageView.layoutIfNeeded()
        })

    }
    
    private func startScan() {
        // 1.是否将输入添加到对话中
        if !session.canAddInput(deviceInput) {
            return
        }
        // 2.是否输出能拿到
        if !session.canAddOutput(deviceOutput) {
            return
        }
        // 3.输入输出添加到会话中
        session.addInput(deviceInput)
        session.addOutput(deviceOutput)
        // 4.设置能够解析的类型
        deviceOutput.metadataObjectTypes = deviceOutput.availableMetadataObjectTypes
        // 5.设置输出代理
        deviceOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        // 6.指定图层
        view.layer.insertSublayer(previewlayer, atIndex: 0)
        
        // 添加绘制图层到预览图层上
        previewlayer.addSublayer(drawLayer)
        
        // 6.告诉session开始扫描
        session.startRunning()
        
        
    }
    
    //MARK: - 懒加载
    // 1.会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    // 2.输入设备
    private lazy var deviceInput: AVCaptureInput? = {
        // 获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            let input = try AVCaptureDeviceInput(device: device)
            return input
        } catch {
            return nil
        }
    }()
    
    // 3.输出设备
    private lazy var deviceOutput: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    // 4.创建预览图层
    private lazy var previewlayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    
    // 5.创建绘制边线的图层
    private lazy var drawLayer: CALayer = {
        let layer = CALayer()
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    
    @IBAction func closebtnClick(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
        
    }

    @IBAction func cardClick(sender: UIButton) {
        let vc = QRCodeCardViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

extension QRCodeViewContoller: AVCaptureMetadataOutputObjectsDelegate {
    // 只要解析到数据 就会调用
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        // 清空图层
        clearConers()
        
        resultLabel.text = metadataObjects.last?.stringValue
        
        // 2.获取扫描的位置
        for object in metadataObjects {
            if object is AVMetadataMachineReadableCodeObject {
                // 2.1转换
                let codeObject = previewlayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                // 3.绘制图形
                drawCorners(codeObject)
            }
        }
        
    }
    /**
     绘制图形
     */
    private func drawCorners(codeObject: AVMetadataMachineReadableCodeObject) {
        
        if codeObject.corners.isEmpty {
            return
        }
        
        // 1.创建图层
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.redColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        // 2.创建路径
//        layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).CGPath
        
        let path = UIBezierPath()
        var point = CGPointZero
        var index: Int = 0
        // 从corners 取出第0个元素给point
        CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)
        path.moveToPoint(point)
        while index < codeObject.corners.count {
            CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)
            path.addLineToPoint(point)
        }
        // 关闭路径
        path.closePath()
        
        layer.path = path.CGPath
        
        // 3.将绘制好的图层添加到drawLayer上
        drawLayer.addSublayer(layer)
    }
    /**
     清空绘制的图形
     */
    private func clearConers() {
        // 判断drawLayer是否有
        if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0 {
            return
        }
        // 清空子图层
        for subLayer in drawLayer.sublayers! {
            subLayer.removeFromSuperlayer()
        }
    }
    
}

